﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twitterizer;
using System.Configuration;
using BO;
using BLL;

namespace MvcApplication1.Controllers
{
    public class TwitterController : Controller
    {
        public ActionResult Oauth()
        {
            var token = OAuthUtility.GetRequestToken(ConfigurationManager.AppSettings["TwitterToken"], ConfigurationManager.AppSettings["TwitterTokenSecret"], "http://localhost:3000/Twitter/Callback");
            var url = OAuthUtility.BuildAuthorizationUri(token.Token);

            return Redirect(url.ToString());
        }

        public ActionResult Callback()
        {
            var token = OAuthUtility.GetAccessTokenDuringCallback(ConfigurationManager.AppSettings["TwitterToken"], ConfigurationManager.AppSettings["TwitterTokenSecret"]);
            var account = Accounts.Get().Where(Accounts.Columns.Name, Actions.Equal, token.ScreenName).SelectOne();
            if (account == null)
            {
                new Account { TwKey = token.Token, TwSecret = token.TokenSecret, Name = token.ScreenName };
                account.Insert();
            }
            else
            {
                account.TwKey = token.Token;
                account.TwSecret = token.TokenSecret;
                account.Name = token.ScreenName;
                account.Update();
            }

            

            ViewBag.Name = account.Name;
            return View();
        }

        public ActionResult Post()
        {
            var accounts = Accounts.Get().Where(Accounts.Columns.TwKey, Actions.NotEqual, null)
                                        .Join(Posts.Get(), Posts.Columns.AccountID)
                        .Select();

            TwitterResponse<TwitterStatus> res;
            foreach (var a in accounts)
                    if(a.Posts != null)
                        foreach (var p in a.Posts)
                            res= TwitterStatus.Update(GetTokens(a), string.Format("@{0} you better stop all that stuff ({1})"
                                                                        , p.FromUserName
                                                                        , p.ForeignID)
                                , new StatusUpdateOptions { InReplyToStatusId = Convert.ToDecimal(p.ForeignID) });


            return null;
            
        }

        public OAuthTokens GetTokens(Account a)
        {
            return new OAuthTokens 
            {
                AccessToken = a.TwKey,
                AccessTokenSecret = a.TwSecret,

                ConsumerKey = ConfigurationManager.AppSettings["TwitterToken"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwitterTokenSecret"]
            };
        }
    }
}
